package com.lcredu.web.exception;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 黎长容
 * @date 2025-07-26 14:10
 */
@Controller
public class MyExceptionHandler {


    //定义局部异常方法
    @ExceptionHandler({ArithmeticException.class, NullPointerException.class})
    public String exceptionShow(Exception exception, HttpServletRequest request) {
        String message = exception.getMessage();
        System.out.println("捕获到异常=" + message);
        request.setAttribute("message", message);
        return "exception_mes";
    }

    //定义一个异常的方法
    @RequestMapping("/getScore")
    public String score(Integer num) {
        int score = 9 / num;
        return "success";
    }


    @RequestMapping("/getString")
    public String getString(String num) {
        int i = Integer.parseInt(num);
        return "success";
    }


    @RequestMapping("/diyException")
    public void diyException() {
        throw new AgeException("年龄必须在1-120之间");
    }


    //统一异常
    @RequestMapping(value = "/testException03")
    public String test03() {
        int[] arr = new int[]{3, 9, 10, 190};
        System.out.println(arr[90]);
        return "success";
    }

    //未知异常
    @RequestMapping(value = "/testException04")
    public String test04() {
        ModelAndView modelAndView = new ModelAndView();
        String str = "hello";
        char c = str.charAt(10);
        return "success";
    }

}
